package com.mi.service.impl;

import com.mi.entity.RoleInfo;
import com.mi.mapper.RoleMapper;
import com.mi.service.RoleService;
import com.mi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    //按条件查询所有的角色
    @Override
    public List<RoleInfo> queryRoles(RoleInfo roleInfo) {
        List<RoleInfo> rolePojos = roleMapper.queryRoles(roleInfo);
        return rolePojos;
    }

    @Override
    public List<RoleInfo> queryAllRole(RoleInfo roleInfo) {
        return roleMapper.queryAllRole(roleInfo);
    }

    //更改角色状态
    @Override
    public boolean updRoleStatus(RoleInfo roleInfo) {
        boolean b = roleMapper.updRole(roleInfo);
        return b;
    }

    //删除一个角色
    @Override
    public boolean delOneRole(String id) {
        boolean b = roleMapper.delRole(id);
        return b;
    }

    //删除多个角色
    @Override
    public boolean delRoles(String ids) {
        boolean b = roleMapper.delRole(ids.substring(0, ids.length() - 1));
        return b;
    }


    /**
     * 添加一个角色
     * @param roleInfo
     * @return
     */
    public boolean addRole(RoleInfo roleInfo) throws Exception {
        boolean b = roleMapper.addRole(roleInfo);
        if(!b){
            throw new Exception("添加用户失败");
        }
        b = roleMapper.addRoleAuths(String.valueOf(roleInfo.getRid()), roleInfo.getAuthss());
        if(!b){
            throw new Exception("添加用户失败");
        }
        return true;
    }

    //更新角色信息
    @Override
    public boolean updRole(RoleInfo roleInfo,String[] str1,String[] str2) throws Exception {
        String[] newAuth = StringUtil.findNo(str1, str2);
        String[] oldAuth = StringUtil.findNo(str2, str1);
        boolean b = roleMapper.updRole(roleInfo);
        if(!b){
            throw new Exception("更新用户失败");
        }
        if(oldAuth.length>0){
            b = roleMapper.delRoleAuths(oldAuth,String.valueOf(roleInfo.getRid()));
        }
        if(!b){
            throw new Exception("更新用户失败");
        }
        if(newAuth.length>0) {
            b = roleMapper.addRoleAuths(String.valueOf(roleInfo.getRid()), newAuth);
        }
        if(!b){
            throw new Exception("更新用户失败");
        }
        return true;
    }

    //获取角色以及所持有的权限
    @Override
    public RoleInfo queryRoleAuth(String rid) {
        return roleMapper.queryRoleAuth(rid);
    }

    //唯一校验
    public boolean soleRole(RoleInfo roleInfo){
        List<RoleInfo> rolePojos = roleMapper.soleRole(roleInfo);
        return rolePojos!=null && rolePojos.size()>0;
    }

}
